<template>
	<view class="page">
		<view class="chat-container">
			<!-- 操作栏 -->
			<view class="action-bar">
				<view class="action-item" @click="clearChatHistory">
					<text class="action-text">清空聊天</text>
				</view>
				
				<view class="action-item ws-btn" @click="goToWsChat">
					<text class="action-text">切换到WebSocket聊天</text>
				</view>
			</view>
			
			<!-- 聊天消息列表 -->
			<scroll-view 
				scroll-y="true" 
				class="chat-list" 
				:scroll-top="scrollTop"
				:scroll-with-animation="true"
				:show-scrollbar="false"
			>
				<view v-for="(item, index) in chatList" :key="index" class="message-item">
					<view :class="['message-content', item.isUser ? 'user-message' : 'ai-message']">
						<view class="avatar">
							<template v-if="item.isUser">
								<include-svg src="/static/avatar/user-avatar.svg"></include-svg>
							</template>
							<template v-else>
								<include-svg src="/static/avatar/ai-avatar.svg"></include-svg>
							</template>
						</view>
						<view class="message-bubble">
							<view class="message-text">{{ item.content }}</view>
						</view>
					</view>
				</view>
				<view class="placeholder" style="height: 20px;"></view>
			</scroll-view>
			
			<!-- 输入区域 -->
			<view class="input-area">
				<input 
					type="text" 
					v-model="inputMessage" 
					placeholder="请输入您的问题" 
					class="message-input"
					@confirm="sendMessage"
				/>
				<button class="send-btn" @click="sendMessage" :disabled="!inputMessage.trim()">发送</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {ref, nextTick, watch} from 'vue';
	import {onLoad, onShow} from "@dcloudio/uni-app";
	import request from "/common/api.js"
	import aiService from "/common/api/ai.js"
	import IncludeSvg from "/components/IncludeSvg.vue";
	
	// 聊天数据
	const chatList = ref([
		{
			isUser: false,
			content: '你好，我是AI助手，有什么可以帮助你的？'
		}
	]);
	
	// 输入框内容
	const inputMessage = ref('');
	
	// 滚动位置
	const scrollTop = ref(0);
	
	// 模型数据
	const model = ref([]);
	
	// 是否正在加载历史记录
	const isLoadingHistory = ref(false);
	
	// 加载历史对话记录
	const loadChatHistory = async () => {
		isLoadingHistory.value = true;
		try {
			const response = await aiService.getAiChatHistory({
				page: 1,
				size: 50
			});
			
			if (response.code === 200 && response.data && response.data.length > 0) {
				// 将历史记录转换为聊天列表格式
				const historyList = [];
				
				response.data.forEach(item => {
					// 添加用户消息
					historyList.push({
						isUser: true,
						content: item.userMessage
					});
					
					// 添加AI回复
					historyList.push({
						isUser: false,
						content: item.aiReply
					});
				});
				
				// 清空欢迎消息，设置历史记录
				chatList.value = historyList;
				
				// 滚动到底部
				await scrollToBottom();
			}
		} catch (error) {
			console.error('加载历史记录失败', error);
			uni.showToast({
				title: '加载历史记录失败',
				icon: 'none'
			});
		} finally {
			isLoadingHistory.value = false;
		}
	};
	
	// 清空聊天记录
	const clearChatHistory = async () => {
		uni.showModal({
			title: '提示',
			content: '确定要清空所有聊天记录吗？',
			success: async (res) => {
				if (res.confirm) {
					try {
						const response = await aiService.clearAiChatHistory();
						
						if (response.code === 200) {
							// 重置为初始欢迎消息
							chatList.value = [{
								isUser: false,
								content: '你好，我是AI助手，有什么可以帮助你的？'
							}];
							
							uni.showToast({
								title: '已清空聊天记录',
								icon: 'success'
							});
						} else {
							uni.showToast({
								title: '清空失败，请稍后再试',
								icon: 'none'
							});
						}
					} catch (error) {
						console.error('清空聊天记录失败', error);
						uni.showToast({
							title: '清空失败，请稍后再试',
							icon: 'none'
						});
					}
				}
			}
		});
	};
	
	// 发送消息
	const sendMessage = async () => {
		if (!inputMessage.value.trim()) return;
		
		// 添加用户消息
		chatList.value.push({
			isUser: true,
			content: inputMessage.value
		});
		
		// 清空输入
		const userMessage = inputMessage.value;
		inputMessage.value = '';
		
		// 滚动到底部
		await scrollToBottom();
		
		// 添加AI正在输入的提示
		chatList.value.push({
			isUser: false,
			content: '正在思考...'
		});
		
		// 请求AI回答
		try {
			const response = await aiService.aiChat({
				message: userMessage
			});
			
			// 更新AI回答
			if (response.code === 200) {
				// 替换"正在思考..."消息
				chatList.value[chatList.value.length - 1] = {
					isUser: false,
					content: response.data || '抱歉，我无法回答这个问题。'
				};
			} else {
				// 替换"正在思考..."消息为错误提示
				chatList.value[chatList.value.length - 1] = {
					isUser: false,
					content: '抱歉，服务出现了问题，请稍后再试。'
				};
			}
		} catch (error) {
			// 替换"正在思考..."消息为错误提示
			chatList.value[chatList.value.length - 1] = {
				isUser: false,
				content: '网络错误，请检查您的网络连接。'
			};
		}
		
		// 再次滚动到底部确保显示最新消息
		await scrollToBottom();
	};
	
	// 滚动到底部方法
	const scrollToBottom = async () => {
		await nextTick();
		const query = uni.createSelectorQuery().in(this);
		query.select('.chat-list').boundingClientRect(data => {
			if (data) {
				scrollTop.value = data.height * 2; // 使用足够大的值确保滚动到底部
			}
		}).exec();
	};
	
	// 监听聊天列表变化，自动滚动到底部
	watch(chatList, () => {
		scrollToBottom();
	}, { deep: true });

	// 跳转到WebSocket聊天页面
	const goToWsChat = () => {
		uni.navigateTo({
			url: '/pages/ai/ws-chat'
		});
	};

	onShow(() => {
		scrollToBottom();
	})

    onLoad(() => {
        request.loadPostData("/appMenu/list", {}, model);
        
        // 加载历史聊天记录
        loadChatHistory();
        
        // 设置导航栏按钮
        uni.setNavigationBarTitle({
            title: 'AI助手'
        });
        
        // 添加清空聊天记录按钮
        uni.setNavigationBarColor({
            frontColor: '#000000',
            backgroundColor: '#ffffff'
        });
        
        uni.showNavigationBarLoading();
        uni.setNavigationBarColor({
            frontColor: '#000000',
            backgroundColor: '#ffffff'
        });
        
        // 设置导航栏右上角按钮
        uni.getSystemInfo({
            success: function(res) {
                // 判断平台
                if (res.platform === 'android' || res.platform === 'ios') {
                    uni.setNavigationBarColor({
                        frontColor: '#000000',
                        backgroundColor: '#ffffff'
                    });
                    
                    // 设置导航栏右侧按钮
                    uni.getMenuButtonBoundingClientRect({
                        success: function(res) {
                            const { width, height, top, right } = res;
                            const navBarHeight = height + (top - uni.getSystemInfoSync().statusBarHeight) * 2;
                            
                            uni.hideNavigationBarLoading();
                        }
                    });
                }
            }
        });
    })
</script>

<style>
	.page {
		width: 100vw;
		height: 100vh;
		background-color: #f5f5f5;
		display: flex;
		flex-direction: column;
	}
	
	.chat-container {
		display: flex;
		flex-direction: column;
		height: 100%;
		position: relative;
		background-color: #f5f5f5;
	}
	
	.action-bar {
		display: flex;
		justify-content: flex-end;
		padding: 20rpx;
		background-color: #ffffff;
		border-bottom: 1px solid #eee;
	}
	
	.action-item {
		padding: 10rpx 30rpx;
		border-radius: 30rpx;
		background-color: #f0f0f0;
		margin-left: 10rpx;
	}
	
	.ws-btn {
		background-color: #e6f7ff;
		border: 1px solid #91d5ff;
	}
	
	.action-text {
		font-size: 24rpx;
		color: #666;
	}
	
	.chat-list {
		flex: 1;
		padding: 20rpx;
		overflow-y: auto;
	}
	
	.message-item {
		margin-bottom: 30rpx;
	}
	
	.message-content {
		display: flex;
		align-items: flex-start;
	}
	
	.user-message {
		flex-direction: row-reverse;
	}
	
	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		overflow: hidden;
		margin: 0 20rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
	}
	
	.avatar image {
		width: 100%;
		height: 100%;
	}
	
	.message-bubble {
		max-width: 70%;
		padding: 20rpx 30rpx;
		border-radius: 10rpx;
		word-break: break-all;
	}
	
	.user-message .message-bubble {
		background-color: #007AFF;
		color: #fff;
		border-top-right-radius: 0;
	}
	
	.ai-message .message-bubble {
		background-color: #fff;
		color: #333;
		border-top-left-radius: 0;
	}
	
	.input-area {
		padding: 20rpx;
		background-color: #fff;
		border-top: 1px solid #eee;
		display: flex;
		align-items: center;
		position: sticky;
		bottom: 0;
		width: 100%;
		box-sizing: border-box;
	}
	
	.message-input {
		flex: 1;
		height: 80rpx;
		background-color: #f0f0f0;
		border-radius: 40rpx;
		padding: 0 30rpx;
		font-size: 28rpx;
		margin-right: 20rpx;
	}
	
	.send-btn {
		width: 140rpx;
		height: 80rpx;
		background-color: #007AFF;
		color: #fff;
		border-radius: 40rpx;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0;
	}
	
	.send-btn:active {
		background-color: #0056b3;
	}
	
	.send-btn[disabled] {
		background-color: #cccccc;
		color: #f5f5f5;
	}
</style>
